package com.study.demo.controller;

import com.study.demo.dao.UserDao;
import com.study.demo.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author WS
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserDao dao;
    @GetMapping
    public ModelAndView list(Model model){
        model.addAttribute("userList",dao.findAll());
        model.addAttribute("title","用户管理列表");
        return new ModelAndView("users/list","userModel",model);
    }
    @GetMapping("/{id}")
    public ModelAndView view(@PathVariable("id")Long id, Model model){
        model.addAttribute("user",dao.findById(id).get());
        model.addAttribute("title","用户查询结果");
        return new ModelAndView("users/view","userModel",model);
    }
    @GetMapping("/form")
    public ModelAndView createForm(Model model){
        model.addAttribute("user",new User(null,"",""));
        model.addAttribute("title","用户添加");
        return new ModelAndView("users/form","userModel",model);
    }
    @PostMapping
    public ModelAndView saveOrUpdateForm(User user){
        dao.save(user);
        return new ModelAndView("redirect:/users");
    }
    @GetMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable("id")Long id, Model model){
        dao.deleteById(id);
        return new ModelAndView("redirect:/users");
    }
    @GetMapping("/modify/{id}")
    public ModelAndView modify(@PathVariable("id")Long id, Model model){
        User user=dao.findById(id).get();
        model.addAttribute("user",user);
        model.addAttribute("title","修改用户");
        return new ModelAndView("users/form","userModel",model);
    }
}
